using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
using System;
using FastCode.Models;
using SqlSugar;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;

namespace FastCode.Middlewares
{
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;

        public GlobalExceptionMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context, ISqlSugarClient db)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                // 记录异常到日志表
                var requestUrl = $"{context.Request.Method} {context.Request.Path}{context.Request.QueryString}";
                var log = new Log
                {
                    LogType = "Exception",
                    UserName = context.User?.Identity?.Name ?? "Anonymous",
                    Content = $"{requestUrl} | {ex}",
                    IP = context.Connection.RemoteIpAddress?.ToString(),
                    OperateTime = DateTime.Now
                };
                db.Insertable(log).ExecuteCommand();

                // 返回详细的错误信息
                context.Response.StatusCode = 500;
                context.Response.ContentType = "application/json";
                
                var errorResponse = new
                {
                    Code = 500,
                    Message = "服务器内部错误",
                    Details = ex.Message,
                    StackTrace = ex.StackTrace,
                    InnerException = ex.InnerException?.Message,
                    Timestamp = DateTime.Now
                };
                
                var jsonResponse = JsonSerializer.Serialize(errorResponse, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });
                
                await context.Response.WriteAsync(jsonResponse);
            }
        }
    }
} 